import React, { Component, useContext, useState, useEffect, useRef } from 'react'
import './WeekTest.css'
import { Select, Input, Space, Button, Table, Switch, Radio, Form, Popconfirm, Typography, Modal, message, InputNumber } from 'antd';
import { SyncOutlined, FormOutlined } from '@ant-design/icons';
import axios from '../../axios/request'



const { Option } = Select;
const { Search } = Input;

// 数据
let originData = [];
// for (let i = 1; i <= 30; i++) {
//   originData.push({
//     key: i,
//     name: `杨传曾${i}`,
//     class: `${i%2===0?'web2':'web4'}`,
//     projectM: '张发贵',
//     sex: `${i%3===0?'女':'男'}`,
//     education: `${i%4===0?'本科':'专科'}`,
//     phone: '13340013322',
//     testResult:parseInt(Math.random()*20+80)
//   });
// }

const EditableContext = React.createContext(null);
// 删除
// const EditableRow = ({ index, ...props }) => {
//   const [form] = Form.useForm();
//   return (
//     <Form form={form} component={false}>
//       <EditableContext.Provider value={form}>
//         <tr {...props} />
//       </EditableContext.Provider>
//     </Form>
//   );
// };
// 编辑
const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: `${title}不能为空!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};
// 选中的人员集合
// let stuSelArr = [];
// 选择框
const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    localStorage.setItem('weekSelArr', JSON.stringify(selectedRows))
  },
  getCheckboxProps: (record) => ({
    disabled: record.name === 'Disabled User',
    // Column configuration not to be checked
    name: record.name,
  }),
};
// 表格配置项
const expandable = { expandedRowRender: record => <p>{record.description}</p> };
const showHeader = true;
const pagination = { position: 'bottom' };

// 批量修改表单组件
const onFinish = (values) => {
  console.log('Success:', values);
};

const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo);
};
const BatchForm = (param) => {
  const [visible, setVisible] = React.useState(false);
  const [data, setData] = useState(originData);
  const [confirmLoading, setConfirmLoading] = React.useState(false);
  // const [modalText, setModalText] = React.useState('Content of the modal');


  const scoresInp = useRef();
  const remarksInp = useRef();
  const showModal = () => {
    let newArr = JSON.parse(localStorage.getItem('weekSelArr')) || [];
    console.log(newArr);
    if (newArr && newArr.length !== 0) {
      setVisible(true);
    } else {
      message.info('请选中需要修改的人员');
    }
  };
  // 确认
  const handleOk = () => {
    // let newData2=[...data];
    let scoresName = scoresInp.current.value;
    let remarksName = remarksInp.current.input.value;
    if (scoresName !== '' && remarksName !== '') {
      param.refreshData(['scores', 'remarks'], [scoresName, remarksName]);
      remarksInp.current.input.value = ''
      scoresInp.current.value = ''
      setConfirmLoading(true);
      setTimeout(() => {
        setVisible(false);
        setConfirmLoading(false);
      }, 2000);
    } else {
      message.info('输入框不能为空！');
    }
  };
  // 取消
  const handleCancel = () => {
    setVisible(false);
  };
  return (
    <>
      <Button type="primary"
        onClick={showModal}
        style={{ marginRight: '10px' }}
        icon={<FormOutlined />}
      >
        选中的全部学员修改
      </Button>
      <Modal
        title="周考成绩修改"
        visible={visible}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
        okText="确认"
        cancelText="取消"
        destroyOnClose
      >
        <Form
          name="batchForm"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item label="周考成绩修改为：">
            <InputNumber placeholder="请输入周考成绩" ref={scoresInp}
              min={1} max={100} defaultValue={100}
            />
          </Form.Item>
          <Form.Item label="备注：">
            <Input placeholder="请输入备注" ref={remarksInp} />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

// 表格函数组件
const TestResults = () => {
  const [form] = Form.useForm();
  const [data, setData] = useState(originData);
  const [editingKey, setEditingKey] = useState('');

  const isEditing = (record) => record.key === editingKey;

  // 获取数据
  const getUserData = () => {
    axios({
      url: '/v1/student/getweekresult',
      method: 'GET',
      headers: {
        'isLoading': true
      }
    }).then(({ data }) => {
      data.data.forEach(ele => {
        ele.key = ele.id;
        ele.remarks = '';
      })
      originData = data.data;
      localStorage.setItem('originDataweek', JSON.stringify(data.data))
      setData(data.data)
    })
  }
  useEffect(() => {
    let allTodo = JSON.parse(localStorage.getItem('originDataweek')) || [];
    // console.log(allTodo);
    if (allTodo.length !== 0) {
      originData = allTodo;
      setData(originData)
    }
    else {
      getUserData()
    }
    return (
      localStorage.setItem('weekSelArr', JSON.stringify([]))
    )
  }, [])
  // 选择
  //  const [selectionType, setSelectionType] = useState('checkbox');
  // 搜索框value
  const searchInp = useRef();
  // 搜索
  const onSearch = value => {
    let seaData = originData.filter(item => {
      return item.name.indexOf(value) !== -1
    })
    searchInp.current.input.value = '';
    setData(seaData);
  };
  // 表单

  // 点击刷新
  const onRefresh = () => {
    window.location.reload();
  }
  const selectInp = useRef();
  const selectClassInp = useRef();
  // 班级选择
  const handleClassChange = (value) => {
    console.log(`selected ${value}`);
    let selData = originData.filter(item => item.classes === value)
    setData(selData);
  }
  // 周考成绩选择
  const handleChange = (value) => {
    console.log(value);
    let allDate = JSON.parse(localStorage.getItem('originDataweek'))
    let selData = [];
    if (value === 'all') {
      selData = allDate;
    }
    if (value === '90') {
      selData = allDate.filter(item => parseInt(item.scores) >= parseInt(value))
    }
    if (value === '89') {
      selData = allDate.filter(item => {
        return parseInt(item.scores) <= parseInt(value)
      })
    }
    setData(selData);
  }

  // 删除事件
  const handleDelete = (key) => {
    let dataSource = [...data];
    dataSource = dataSource.filter((item) => item.key !== key);
    setData(dataSource);
  };
  // 编辑
  const edit = (record) => {
    form.setFieldsValue({
      testResult: '',
      ...record,
    });
    setEditingKey(record.key);
  };
  // 页数
  const cancel = () => {
    setEditingKey('');
  };
  // 保存
  const save = async (key) => {
    try {
      const row = await form.validateFields();
      const newData = JSON.parse(localStorage.getItem('originDataweek'))
      const index = newData.findIndex((item) => key === item.key);
      console.log(row);
      // let idCard = newData[index].idcard;
      // console.log(idCard);
      // axios({
      //   url: 'v1/student/updatecredit',
      //   method: 'POST',
      //   headers: {
      //     'isLoading': true
      //   },
      //   data:{idcard:idCard,credit:row.scores}
      // }).then(({ data }) => {
      //   console.log(data);
      //   getUserData()
      //   console.log(originData);
      // data.data.forEach(ele => {
      //   ele.key = ele.id;
      //   ele.remarks = '';
      // })
      // originData = data.data;
      // localStorage.setItem('originDataweek', JSON.stringify(data.data))
      // setData(data.data)
      // })

      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        setData(newData);
        localStorage.setItem('originDataweek', JSON.stringify(newData))
        setEditingKey('');
      } else {
        newData.push(row);
        setData(newData);
        localStorage.setItem('originDataweek', JSON.stringify(newData))
        setEditingKey('');
      }

    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };
  // 更新数据
  const refreshData = (typeName, record) => {
    // console.log(typeName, record);
    let selectedRows = JSON.parse(localStorage.getItem('weekSelArr'))
    for (let ind = 0; ind < typeName.length; ind++) {
      selectedRows.forEach((item) => {
        item[typeName[ind]] = record[ind]
        data.forEach((i, index) => {
          if (i.key === item.key) {
            data.splice(index, 1)
          }
        })
      })
    }
    let newArr = [...selectedRows, ...data]
    newArr.sort((a, b) => {
      return a.key - b.key
    })
    localStorage.setItem('originDataweek', JSON.stringify(newArr))
    setData(newArr)
  }
  // 行数据配置
  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      sorter: (a, b) => a.key - b.key,
      width: '8%',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '班级',
      dataIndex: 'classes',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '项目经理',
      dataIndex: 'teacher',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '性别',
      dataIndex: 'sex',
      align: 'center',
      width: '6%',
      ellipsis: true,
    },
    {
      title: '学历',
      dataIndex: 'education',
      align: 'center',
      width: '8%',
      ellipsis: true,
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '周考成绩',
      dataIndex: 'scores',
      align: 'center',
      ellipsis: true,
      editable: true,
      sorter: (a, b) => a.testResult - b.testResult,
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      align: 'center',
      ellipsis: true,
      editable: true,
    },
    {
      title: '修改',
      key: 'revise',
      align: 'center',
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Typography.Link
              onClick={() => save(record.key)}
              style={{
                marginRight: 8,
              }}
            >
              保存
            </Typography.Link>
            <Popconfirm title="确认取消吗?" onConfirm={cancel}>
              <a>取消</a>
            </Popconfirm>
          </span>
        ) : (
          <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
            编辑
          </Typography.Link>
        );
      },
    },
    // {
    //   title: '删除',
    //   key: 'delete',
    //   align: 'center',
    //   render: (_, record) =>
    //     originData.length >= 1 ? (
    //       <Popconfirm title="您确认删除吗?" onConfirm={() => handleDelete(record.key)}>
    //         <a>删除</a>
    //       </Popconfirm>
    //     ) : null,
    // },
  ];

  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record) => ({
        record,
        // inputType: col.dataIndex === 'age' ? 'number' : 'text',
        inputType: col.dataIndex === 'age' ? 'number' : 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  return (
    <div>
      <div className='WeekTest'>
        <div className='table_fun'>
          <div className='class_sel'>
            所属班级：
            <Select defaultValue="NC2021WEB2" style={{ width: 135, marginRight: '10px' }} onChange={handleClassChange} ref={selectClassInp}>
              <Option value="NC2021WEB2">NC2021WEB2</Option>
              <Option value="NC2021WEB4">NC2021WEB4</Option>
              {/* <Option value="java2">java2</Option>
              <Option value="java4">java4</Option> */}
            </Select>
          </div>
          <div className='class_inp'>
            <span>学员姓名：</span>
            <Search placeholder="请输入学员名称" onSearch={onSearch} enterButton
              ref={searchInp}
            />
          </div>
          {/* <Button
            type="primary"
            icon={<FolderOpenOutlined />}
            style={{ marginRight: '10px' }}
          >
            全部
          </Button> */}
          <Button
            type="primary"
            icon={<SyncOutlined />}
            style={{ marginRight: '10px' }}
            onClick={onRefresh}
          >
            刷新
          </Button>
          <BatchForm refreshData={refreshData} />
          <div className='class_sel'>
            成绩分类：
            <Select defaultValue="all" style={{ width: 140 }} onChange={handleChange} ref={selectInp}>
              <Option value="all">全部</Option>
              <Option value="90">90分及90分以上</Option>
              <Option value="89">90分以下</Option>
              {/* <Option value="java2">java2</Option>
              <Option value="java4">java4</Option> */}
            </Select>
          </div>
        </div>
        <div className='table_box'>
          <Form form={form} component={false}>
            <Table
              components={{
                body: {
                  // row: EditableRow,
                  cell: EditableCell,
                },
              }}
              bordered
              dataSource={data}
              columns={mergedColumns}
              rowClassName="editable-row"
              pagination={{
                onChange: cancel,
              }}
              rowSelection={rowSelection}
              scroll={
                {
                  y: 540
                }
              }
            />
          </Form>
        </div>
      </div>
    </div>
  );
};

export default TestResults


